from flask import Blueprint, request, jsonify
from compile.Question import Question
from compile.Task import Task
from dao.ProblemDao import ProblemDAO

compile_bp = Blueprint('compile', __name__, url_prefix='/execute')


def merge_code(request_str, test_code):
    pos = request_str.rfind("}")
    if pos == -1:
        return None
    substr = request_str[:pos]
    return f"public {substr}{test_code}\n}}"


@compile_bp.route('/compile', methods=['POST'])
def compile():
    data = request.json
    problem_dao = ProblemDAO()
    problem = problem_dao.select_one(data['id'])

    if not problem:
        return jsonify({"error": 3, "reason": "没有该题"}), 404

    test_code = problem.testCode
    request_code = data['code']
    final_code = merge_code(request_code, test_code)

    if not request_code:
        return jsonify({"error": 4, "reason": "提交代码不符合要求！"}), 400

    question = Question(data['id'], final_code)
    task = Task()
    answer = task.compile_and_run(question)
    return jsonify(answer.to_dict())